package com.zxk.blog.controller;

import com.zxk.core.common.util.JsonData;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@Api("文件服务，由于服务器配置问题，若配置私服则有时会报错")
@RequestMapping("/blog/api/file")
public class FileController {

    @Value("${web.file.path}")
    private String filePath;

    @PostMapping("/upload-file")
    public JsonData upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        //file.isEmpty(); 判断图片是否为空
        //file.getSize(); 图片大小进行判断

        System.out.println("配置注入打印，文件路径为："+filePath);


        String name = request.getParameter("name");
        System.out.println("用户名："+name);
        if(null == name || !name.equals("zxk")) {
            throw new RuntimeException("姓名不对，禁止上传！！");
        }

        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为：" + fileName);

        // 获取文件的后缀名,比如图片的jpeg,png
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为：" + suffixName);

        // 文件上传后的路径
        fileName = UUID.randomUUID() + suffixName;
        System.out.println("转换后的名称:"+fileName);

        File dest = new File(filePath + fileName);

        try {
            file.transferTo(dest);

            return new JsonData(0, fileName,"success");
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  new JsonData(-1, "fail to save ", null);
    }
}
